package com.hanbang.taitaigou.utils.ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.widget.swipemenulistview.SwipeMenuListView;
import com.hanbang.taitaigou.utils.http.PagingHelp;
import com.hanbang.taitaigou.utils.other.ObjectUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class UiUtils {
    /**
     * 获得一个空间的宽高   防0
     */

    public static void setViewMeasure(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, null);
        applyFont(view);
        return view;
    }

    /**
     * 从资源文件获取一个view
     */
    public static View getInflaterView(Context context, int res, ViewGroup parent) {
        View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(res, parent);
        applyFont(view);
        return view;
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context 某个界面名称
     */
    public static boolean isForeground(Context context) {
        if (context instanceof Activity) {
            String className = context.getClass().getName();
            if (context == null || TextUtils.isEmpty(className)) {
                return false;
            }

            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> list = am.getRunningTasks(1);
            if (list != null && list.size() > 0) {
                ComponentName cpn = list.get(0).topActivity;
                if (className.equals(cpn.getClassName())) {
                    return true;
                }
            }
        }
        return false;

    }

	/*
     * listview item 3d delete
	 */

    public static void deleteItemAnimationRotationX(final View item,
                                                    final List<?> listDatas, final int position,
                                                    final PagingHelp pagingHelp, final SwipeMenuListView listView, int duration) {
        final int originHeight = item.getMeasuredHeight();
        final int originWidth = item.getMeasuredWidth();
        ObjectAnimator alpha = ObjectAnimator.ofFloat(item, "alpha", 0.5f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(item, "rotationX", -80);
        item.setPivotX(originWidth / 2);
        scaleY.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator value) {
                float cVal = (float) value.getCurrentPlayTime()
                        / value.getDuration();
                item.getLayoutParams().height = (int) (originHeight - originHeight
                        * cVal);
                item.requestLayout();

            }
        });
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(alpha).with(scaleY);
        animatorSet.setDuration(duration);
        animatorSet.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator arg0) {
                listDatas.remove(position);
                item.setRotationX(0);
                item.setAlpha(1);
                item.setPivotX(0);
                if (pagingHelp != null) {
                    pagingHelp.deleteOneItem();
                }
                ((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
            }

        });
        animatorSet.start();
    }

    public static void deleteItemAnimationRotationX(final View item,
                                                    final List<?> listDatas, final int position, final SwipeMenuListView listView, int duration) {
        deleteItemAnimationRotationX(item, listDatas, position, null, listView, duration);
    }

    public static void deleteItemAnimationRotationX(final View item,
                                                    final List<?> listDatas, final int position, final SwipeMenuListView listView) {
        deleteItemAnimationRotationX(item, listDatas, position, null, listView, 400);
    }

    /*
     * 上下抖动动画，用于提醒用户去点击 rotation:转动角度,
     */
    public static void shakeUp(View view, float scaleMax, float rotation) {
        // Keyframe是一个时间/值对，用于定义在某个时刻动画的状态
        // 在不同时间段的X轴0.8-1.1的缩放
        PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofKeyframe(
                "scaleX", Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(0.1f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.2f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.3f, scaleMax),
                Keyframe.ofFloat(0.4f, scaleMax),
                Keyframe.ofFloat(0.5f, scaleMax),
                Keyframe.ofFloat(0.6f, scaleMax),
                Keyframe.ofFloat(0.7f, scaleMax),
                Keyframe.ofFloat(0.8f, scaleMax),
                Keyframe.ofFloat(0.9f, scaleMax), Keyframe.ofFloat(1f, 1f));
        // 在不同时间段的Y轴0.8-1.1的缩放
        PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofKeyframe(
                "scaleY", Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(0.1f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.2f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.3f, scaleMax),
                Keyframe.ofFloat(0.4f, scaleMax),
                Keyframe.ofFloat(0.5f, scaleMax),
                Keyframe.ofFloat(0.6f, scaleMax),
                Keyframe.ofFloat(0.7f, scaleMax),
                Keyframe.ofFloat(0.8f, scaleMax),
                Keyframe.ofFloat(0.9f, scaleMax), Keyframe.ofFloat(1f, 1f));

        // 在不同时间段的旋转 旋转角度 = 0.3*抖动系数
        PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe(
                "rotation", Keyframe.ofFloat(0f, 0f),
                Keyframe.ofFloat(0.1f, rotation),
                Keyframe.ofFloat(0.2f, -rotation),
                Keyframe.ofFloat(0.3f, rotation),
                Keyframe.ofFloat(0.4f, -rotation),
                Keyframe.ofFloat(0.5f, rotation),
                Keyframe.ofFloat(0.6f, -rotation),
                Keyframe.ofFloat(0.7f, rotation),
                Keyframe.ofFloat(0.8f, -rotation),
                Keyframe.ofFloat(0.9f, rotation), Keyframe.ofFloat(1f, 0f));
        ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(
                view, pvhScaleX, pvhScaleY, pvhRotation).setDuration(1000);
        objectAnimator.start();

    }

    /*
     * 左右抖动动画，用于表单验证失败 translation:平移距离,
     */
    public static void shakeLeft(View view, float scaleMax, float translation) {
        translation = ObjectUtils.dip2px(view.getContext(), translation);
        // Keyframe是一个时间/值对，用于定义在某个时刻动画的状态
        // 在不同时间段的X轴0.8-1.1的缩放
        PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofKeyframe(
                "scaleX", Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(0.1f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.2f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.3f, scaleMax),
                Keyframe.ofFloat(0.4f, scaleMax),
                Keyframe.ofFloat(0.5f, scaleMax),
                Keyframe.ofFloat(0.6f, scaleMax),
                Keyframe.ofFloat(0.7f, scaleMax),
                Keyframe.ofFloat(0.8f, scaleMax),
                Keyframe.ofFloat(0.9f, scaleMax), Keyframe.ofFloat(1f, 1f));
        // 在不同时间段的Y轴0.8-1.1的缩放
        PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofKeyframe(
                "scaleY", Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(0.1f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.2f, scaleMax - 0.3f),
                Keyframe.ofFloat(0.3f, scaleMax),
                Keyframe.ofFloat(0.4f, scaleMax),
                Keyframe.ofFloat(0.5f, scaleMax),
                Keyframe.ofFloat(0.6f, scaleMax),
                Keyframe.ofFloat(0.7f, scaleMax),
                Keyframe.ofFloat(0.8f, scaleMax),
                Keyframe.ofFloat(0.9f, scaleMax), Keyframe.ofFloat(1f, 1f));

        // 在不同时间
        PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe(
                "translationX", Keyframe.ofFloat(0f, 0f),
                Keyframe.ofFloat(0.1f, translation),
                Keyframe.ofFloat(0.2f, -translation),
                Keyframe.ofFloat(0.3f, translation),
                Keyframe.ofFloat(0.4f, -translation),
                Keyframe.ofFloat(0.5f, translation),
                Keyframe.ofFloat(0.6f, -translation),
                Keyframe.ofFloat(0.7f, translation),
                Keyframe.ofFloat(0.8f, -translation),
                Keyframe.ofFloat(0.9f, translation), Keyframe.ofFloat(1f, 0f));
        ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(
                view, pvhScaleX, pvhScaleY, pvhRotation).setDuration(1000);
        objectAnimator.start();

    }

    /**
     * 缩放动画，先放大，后缩小，   用于提醒用户状态的变化
     */
    public static void scaleAnim(View view, float scaleMax, float scaleMin, int duration) {

        PropertyValuesHolder scx = PropertyValuesHolder.ofFloat("scaleX", 1, scaleMax, 1, scaleMin, 1);
        PropertyValuesHolder scY = PropertyValuesHolder.ofFloat("scaleY", 1, scaleMax, 1, scaleMin, 1);

        ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(
                view, scx, scY).setDuration(duration);
        objectAnimator.start();


    }


    public static void setButton(ViewGroup ll, boolean press) {
        if (press) {
            ll.setEnabled(false);
            ll.getChildAt(0).setEnabled(false);
        } else {
            ll.setEnabled(true);
            ll.getChildAt(0).setEnabled(true);
        }
    }


    /**
     * 设置按钮的点击效果  只能设置ImageView  和TextView
     */
    public static void setButtonClickTint(final View view, final int colorUp,
                                          final int colorDown) {
        view.setClickable(true);
        if (view instanceof ImageView) {
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            ((ImageView) view).setColorFilter(view.getResources()
                                    .getColor(colorDown));
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            ((ImageView) view).setColorFilter(view.getResources()
                                    .getColor(colorUp));
                            break;

                        default:
                            break;
                    }

                    return false;
                }
            });
            // 设置字体点击后的文字颜色变化
        } else if (view instanceof TextView) {
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {

                        case MotionEvent.ACTION_DOWN:

                            ((TextView) view).setTextColor(view.getResources()
                                    .getColor(colorDown));
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            ((TextView) view).setTextColor(view.getResources()
                                    .getColor(colorUp));
                            break;

                        default:
                            break;
                    }

                    return false;
                }
            });
        } else if (view instanceof ViewGroup) {
            view.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            setViewGroupTint((ViewGroup) v, colorDown);
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            setViewGroupTint((ViewGroup) v, colorUp);
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            });
        }
    }

    /*
     * 设置ImageView渲染（Tint）
     */
    public static void setImageViewTint(final ImageView view, final int color) {
        view.setColorFilter(view.getResources().getColor(color));
    }

    /*
    * 设置ViewGroup渲染（Tint）
    */
    public static void setViewGroupTint(ViewGroup view, int color) {
        for (int i = 0; i < view.getChildCount(); i++) {
            View child = view.getChildAt(i);
            if (child instanceof ImageView) {
                setImageViewTint((ImageView) child, color);
            } else if (child instanceof TextView) {
                ((TextView) child).setTextColor(view.getResources()
                        .getColor(color));
            } else if (child instanceof ViewGroup) {
                setViewGroupTint((ViewGroup) child, color);
            }
        }
    }

    /*
     * 设置字体
     */
    public static void applyFont(final View root) {
        try {
            if (root instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) root;
                for (int i = 0; i < viewGroup.getChildCount(); i++)
                    applyFont(viewGroup.getChildAt(i));
            } else if (root instanceof TextView)
                ((TextView) root).setTypeface(((MyApplication) (root
                        .getContext().getApplicationContext())).typeface);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static View getRootView(Activity context) {
        return context.getWindow().getDecorView()
                .findViewById(android.R.id.content);
    }

    /*
     * 设置按钮点击后的渲染（Tint）
     */
    public static void setButtonClickTint(final ImageView view,
                                          final int colorUp, final int colorDown) {
        view.setOnTouchListener(new OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        view.setColorFilter(view.getResources().getColor(colorUp));
                        break;
                    case MotionEvent.ACTION_DOWN:
                        view.setColorFilter(view.getResources().getColor(colorDown));
                        break;

                    default:
                        break;
                }

                return false;
            }
        });
    }

    /**
     * 加入购物车的动画
     */
    public static void addGwcAnim() {

    }




    /**
     * 开启拍照
     */

    public static String startPaiZhao(Activity context, int requestCode) {
        File fDir = new File(MyApplication.appSDCachePath);
        String cachePath = System.currentTimeMillis() + ".jpg";
        if (fDir.exists() || fDir.mkdirs()) {
            File cameraFile = new File(fDir, cachePath);
            if (!cameraFile.exists()) {
                try {
                    cameraFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
            context.startActivityForResult(intent, requestCode);
        }
        return cachePath;
    }

    /**
     * 开启文件选择
     */
    public static void startFileSelect(Activity context, String Type, int requestCode) {
        Intent intent = new Intent();
        intent.setType(Type);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.putExtra("return-data", true);
        context.startActivityForResult(intent, requestCode);
    }
}